package com.zui.webapp.support;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HttpServletBean;

/**
 * 
 * @author Sam
 * @since 1.0
 */
public class DBExportServlet extends HttpServletBean {

	private static final long serialVersionUID = 1L;

	private String datasetDirectory;
	/**
	 * xls or xml
	 */
	private String datasetFormat;
	private boolean enabled;

	@Override
	protected void initServletBean() throws ServletException {
		if (enabled)
			exportDB();
	}

	/**
	 * database population with dbunit
	 * 
	 */
	@Override
	protected final void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		exportDB();
		/**
		 * @TODO:wirte success response.
		 */

	}

	private void exportDB() {

		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		
		if (datasetDirectory == null)
			datasetDirectory =  "/WEB-INF/datasets";

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HH_mm");
		Date currentDate = Calendar.getInstance().getTime();
		String datasetLocation = datasetDirectory + "/dataSet_exported_" + sdf.format(currentDate) + "." + datasetFormat;
		
		if ("xls".equalsIgnoreCase(datasetFormat)) {
			new XlsDataSetOperator(ctx, datasetLocation).exportDataSet();
		} else if ("xml".equalsIgnoreCase(datasetFormat)) {
			new XmlDataSetOperator(ctx, datasetLocation).exportDataSet();
		}
		
		if (logger.isDebugEnabled()) {
			logger.debug("The full table schema was exported to \"" + datasetLocation + "\" using DBUnit.");
		}
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public String getDatasetFormat() {
		return datasetFormat;
	}

	public void setDatasetFormat(String datasetFormat) {
		this.datasetFormat = datasetFormat;
	}

	public String getDatasetDirectory() {
		return datasetDirectory;
	}

	public void setDatasetDirectory(String datasetDirectory) {
		this.datasetDirectory = datasetDirectory;
	}

}
